package com.lky.marshallmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.lky.common.constant.ProductConstant;
import com.lky.common.to.SkuReductionTo;
import com.lky.common.to.SpuBoundsTo;
import com.lky.common.to.es.SkuEsModle;
import com.lky.common.utils.R;
import com.lky.marshallmall.product.dao.SpuInfoDescDao;
import com.lky.marshallmall.product.entity.*;
import com.lky.marshallmall.product.feign.CouponFeignService;
import com.lky.marshallmall.product.feign.SearchFeignService;
import com.lky.marshallmall.product.feign.WareFeignService;
import com.lky.marshallmall.product.service.*;
import com.lky.marshallmall.product.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lky.common.utils.PageUtils;
import com.lky.common.utils.Query;

import com.lky.marshallmall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService descService;
    @Autowired
    private SpuImagesService imagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService saleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * TODO 个别保存失败的回滚
     * @GlobalTransactional seata AT事务
     * @param vos
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vos) {
        //1.保存spu基本信息；pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vos,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //2.保存spu的描述图片；pms_spu_info_desc
        List<String> decripts = vos.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",",decripts));
        descService.saveSpuInfoDescript(descEntity);
        //3.保存spu的图片集；pms_spu_images
        List<String> images = vos.getImages();
        imagesService.saveSpuImages(spuInfoEntity.getId(),images);
        //4，保存spu的规格参数；pms_product_attr_value
        List<BaseAttrs> baseAttrs = vos.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc()); //1 快速展示
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);
        //5. 保存spu级分信息；sms_spu_bounds（sms数据库，积分信息） //TODO 远程库
        Bounds bounds = vos.getBounds();
        //两个服务远程交互的实体类（VO）
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r1.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }

        //6，保单当前spu对应的所有sku信息
        //6.1 sku基本信息；pms_sku_info
        List<Skus> skus = vos.getSkus();
        if (skus!=null && skus.size()>0){
            skus.forEach(sku->{
                //找到默认显示的图片
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg()==1){
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuEntity);
                skuEntity.setBrandId(spuInfoEntity.getBrandId());
                skuEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuEntity.setSaleCount(0L);
                skuEntity.setSpuId(spuInfoEntity.getId());
                skuEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuEntity);
                //SKU自增主键Id
                Long skuId = skuEntity.getSkuId();
                //6.2 sku图片信息；pms_sku_images
                List<SkuImagesEntity> imageLists = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter((item)->{
                    //返回true需要，返回false会过滤
                    return !StringUtils.isEmpty(item.getImgUrl());
                }).collect(Collectors.toList());
                //TODO 没有图片路径的，无需保存
                skuImagesService.saveBatch(imageLists);
                //6.3 sku的销售属性信息；pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                saleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //6.4 sku的优惠满减信息；
                // sms数据库 sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount()>0&&skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }



    }

    //1.保存spu基本信息；pms_spu_info
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((w)->{
              w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        //查出当前spuid对应的sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //TODO 查询当前sku所有规格属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModle.Attrs> attrs = new ArrayList<>();
        List<SkuEsModle.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item->{
            SkuEsModle.Attrs attrs1 = new SkuEsModle.Attrs();
            BeanUtils.copyProperties(item,attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        //TODO 调用库存系统 是否有库存
        //调用失败依然保存
        Map<Long, Boolean> stockMapping = null;
        try{
            R r = wareFeignService.getSkuHasStock(skuIdList);
            TypeReference<List<SkuHashStockVo>> typeReference = new TypeReference<List<SkuHashStockVo>>() {
            };
            List<SkuHashStockVo> data = (List<SkuHashStockVo>) r.getData(typeReference);
            stockMapping = data.stream().collect(Collectors.toMap(SkuHashStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常,原因{}"+e);
        }

        //封装每个Sku信息
        Map<Long, Boolean> finalStockMapping = stockMapping;
        List<SkuEsModle> upProducts = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModle esModle = new SkuEsModle();
            BeanUtils.copyProperties(sku,esModle);
            esModle.setSkuPrice(sku.getPrice());
            esModle.setSkuImg(sku.getSkuDefaultImg());
            esModle.setCatelogId(sku.getCatalogId());
            //（每次都远程调用，资源浪费,在流外远程调用）
            if (finalStockMapping ==null){
                esModle.setHasStock(true);
            }else {
                esModle.setHasStock(finalStockMapping.get(sku.getSkuId()));
            }
            //TODO 热度评分
            esModle.setHotScore(0L);
            //查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(esModle.getBrandId());
            esModle.setBrandName(brand.getName());
            esModle.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(esModle.getCatelogId());
            esModle.setCatelogId(category.getCatId());
            esModle.setCatelogName(category.getName());
            //设置检索属性
            esModle.setAttrs(attrsList);
            return esModle;
        }).collect(Collectors.toList());

        //TODO 将数据发送给es进行保存，marshall-search
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode()==0){
            //TODO 修改spu状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //TODO 重复调用?接口幂等性?重试机制?
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity sku = skuInfoService.getById(skuId);
        Long spuId = sku.getSpuId();
        SpuInfoEntity spu = getById(spuId);
        return spu;
    }


}